<?php

namespace Framework\Foundation\Validator;

use Filterus\Filter;

class Validator
{
    public function validate($rules, $data)
    {
        return Filter::map($rules)->validate($data);
    }

    public function validWithMsg($rules, $data, $msg)
    {
        $errorMsg = [];
        foreach ($rules as $key => $rule) {
            if (!isset($data[$key])) {
                if (isset($msg[$key]['required'])) {
                    $errorMsg[$key] = empty($msg[$key]['required']) ? $key . ' is required' : $msg[$key]['required'];
                }
                continue;
            }

            if (!Filter::factory($rule)->validate($data[$key])) {
                $errorMsg[$key] = isset($msg[$key]['invalid']) ? $msg[$key]['invalid'] : $msg[$key];
            }
        }

        return $errorMsg;
    }

    public function validRowsWithMsg($rules, $data, $msg)
    {
        $errorMsg = [];
        foreach ($data as $row) {
            $ret = $this->validWithMsg($rules, $row, $msg);
            if (!empty($ret)) {
                $errorMsg[] = $ret;
            }
        }
        return $errorMsg;
    }

    public function filter($rules, $data)
    {
        foreach ($rules as $key => $rule) {
            if (!isset($data[$key])) {
                continue;
            }

            $data[$key] = Filter::factory($rule)->filter($data[$key]);
        }

        return $data;
    }

    public function filterRows($rules, $data)
    {
        foreach ($data as $k => $row) {
            $data[$k] = $this->filter($rules, $row);
        }
        return $data;
    }
}
